//
//  BasicService.m
//  WebServices
//
//  Created by psvn047 on 5/10/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "BasicHttpService.h"
#define HTTP_HOST @"http://api.int.playlive.playsoft.fr/"
#define CONSUMER_KEY @"4e3c83844e4b11e1a29e12313b050c9b"
#define SECRET_KEY @"YTY2NmMyMTE1Y2Q1NDQ1MDhlMTc0YmZlYWE4MTQ2NGY="
#define APPLICATION_NAME @"Playlive iOS SDK"
#define VERSION @"1.0.0"
#define DEBUG_MODE 1

@implementation BasicHttpService
@synthesize serviceCallbackDelegate;
@synthesize responseData;
@synthesize serviceID;

static Session * session;
+(void) setSession:(Session*) sessionObj
{
    session = sessionObj;
}
+(Session*) getSession
{
    return session;
}
-(Application*) getApplication
{
    ApiKey* apiKey = [[ApiKey alloc] init];
    [apiKey initApiKey:SECRET_KEY consumerKey:CONSUMER_KEY];
    //[apiKey initApiKey:@"MzFlYTY4NWJlNDcxNDdlYWI0NDNhZjIyMjhkYTE4MjM=" consumerKey:@"c15e30e03b4711e1970712313b050c9b"];
    Application * app = [[Application alloc] init];
   [app initApplication:APPLICATION_NAME version:VERSION apiKey:apiKey];
    return app;
}
-(NSString*) getHTTPHost
{
    return HTTP_HOST;
}
-(void) callService:(NSString*) serviceId httpMethod:(NSString*) httpMethod httpHost: (NSString*) httpHost path:(NSString*) path queryParameters: (NSMutableDictionary*) queryParameters messageBody:(NSString*) messageBody application: (Application*) application session:(Session*) session 
{
    serviceID = serviceId;
    
    NSString* urlString = [NSString stringWithFormat:@"%@%@", httpHost, path];
    NSURL *url = [NSURL URLWithString:urlString];
    NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];   
    
    [urlRequest addValue:@"gzip, deflate" forHTTPHeaderField:@"Accept-Encoding"];
    [urlRequest addValue:messageBody forHTTPHeaderField:@"Content-Length"];
    //[urlRequest setHTTPMethod:@"POST"];
    [urlRequest setHTTPMethod:httpMethod];
    //use custom header for right method, such as GET, DELETE, OPTIONS...
    //if([httpMethod compare:@"GET"] != NSOrderedSame)
    //{
    //    [urlRequest addValue:httpMethod forHTTPHeaderField:@"X-HTTP-Method-Override"];
    //}
    if(session)
    {
         [urlRequest addValue:session.authToken forHTTPHeaderField:@"X-Authentication"];
    }
    if(application)
    {
        ApiKey * apiKey = application.apiKey;
        [urlRequest addValue:apiKey.consumerKey forHTTPHeaderField:@"X-API-Key"];
        [urlRequest addValue:[apiKey getURLSignature:NULL] forHTTPHeaderField:@"X-API-Sig"];
        [urlRequest addValue:NULL forHTTPHeaderField:@"User-Agent"];
    }
    if(DEBUG_MODE) NSLog(@"[ServiceID:] %@ [Link:] %@ ", self.serviceID, [urlRequest URL]);
    if(queryParameters)
    {
        //SBJsonWriter * jWriter = [[SBJsonWriter alloc] init];
        //NSData * data = [jWriter dataWithObject:queryParameters];
        
        [urlRequest setHTTPBody:[queryParameters JSONData]];
        if(DEBUG_MODE) NSLog(@"[ServiceID:] %@ [Parameters:] %@ ", self.serviceID, [queryParameters JSONString]);
    }
    
     NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];
     if(connection) {
         responseData = [[NSMutableData alloc] init];
     } else {
         if(DEBUG_MODE) NSLog(@"Connection Failed");
         NSMutableDictionary * errDict = [NSMutableDictionary dictionary];
         [errDict setObject:@"Connection Failed" forKey:@"message"];
         [errDict setObject:@"ConnectionErrorException" forKey:@"error"];
         [serviceCallbackDelegate failedCallback:self.serviceID reponseData:errDict];
     }
}
-(void) callServiceSuccessed:(NSString*) serviceId reponseData:(NSObject*) data
{
    [serviceCallbackDelegate successedCallback:self.serviceID reponseData:data];
}
-(void) callserviceFailed:(NSString*) serviceId reponseData:(NSObject*) data
{
    if([data isKindOfClass:[NSError class]])
    {
        NSMutableDictionary * errDict = [NSMutableDictionary dictionary];
        NSError * err = (NSError*) data;
        [errDict setObject:[err localizedDescription] forKey:@"message"];
        [errDict setObject:@"ConnectionErrorException" forKey:@"error"];
        [serviceCallbackDelegate failedCallback:self.serviceID reponseData:errDict];
    }
    else
    {
         [serviceCallbackDelegate failedCallback:self.serviceID reponseData:data];
    }
}

#pragma mark - NSURLConnection delegate methods
- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    [responseData setLength:0];
    
	if( [response respondsToSelector:@selector(statusCode)] )
	{
		// check response status code
		statusCode = [((NSHTTPURLResponse *)response) statusCode];
	}
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [responseData appendData:data];    
}

- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    
    if(DEBUG_MODE) NSLog(@"[ServiceID:] %@ [Reponse Data:] %@", self.serviceID, error.localizedDescription);
    [self callserviceFailed:self.serviceID reponseData:error];
    [connection release];
    [responseData release];
}

- (void) connectionDidFinishLoading:(NSURLConnection *)connection
{
    JSONDecoder *decoder = [[[JSONDecoder alloc] initWithParseOptions:JKParseOptionNone] autorelease];
    NSObject* json = [decoder objectWithData:responseData];
    //if(DEBUG_MODE) NSLog(@"[ServiceID:] %@ [Reponse Data:] %@", self.serviceID, [json JSONString]);
    
    if( statusCode != 200 )
    {
        NSMutableDictionary * query = [NSMutableDictionary dictionary];
        [query setObject:[(NSDictionary*) json objectForKey:@"message" ] forKey:@"message"];
        [query setObject:[(NSDictionary*) json objectForKey:@"error" ] forKey:@"error"];
        //[query setObject:[NSString stringWithFormat:@"%d",statusCode] forKey:@"statusCode"];
         [self callserviceFailed:self.serviceID reponseData: query];
    }
    else {
      
        [self callServiceSuccessed:self.serviceID reponseData: json];
    }
    [connection release];
}

- (void)dealloc
{
    [super dealloc];
    [serviceCallbackDelegate release];
    [responseData release];
    [serviceID release];
}
@end
